package com.snack.common.code;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类 2010-8-6上午10:40:51 MD5
 * 
 * @author lamfire
 */
public class MD5 {

	public static String sign(String message) {
		byte[] encode = getMessageDigest().digest(message.getBytes());
		return HEX.encodeHexString(encode);
	}
	
	public static String hash(String message) {
		byte[] encode = getMessageDigest().digest(message.getBytes());
		return HEX.encodeHexString(encode);
	}
	
	public static String hash(File file) throws IOException {
		InputStream fis = null;
		MessageDigest digest = getMessageDigest();
		try{
			fis = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int numRead = 0;
			while ((numRead = fis.read(buffer)) > 0) {
				digest.update(buffer, 0, numRead);
			}
		}catch(IOException e){
			throw e;
		}finally{
			if(fis != null){
				fis.close();
			}
		}
		byte[] encode = digest.digest();
		return HEX.encodeHexString(encode);
	}

	public static byte[] digest(byte[] data) {
		return getMessageDigest().digest(data);
	}

	public static String digestHex(byte[] data) {
		return HEX.encodeHexString(digest(data));
	}

	public static MessageDigest getMessageDigest() {
		try {
			return MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}

	}

}